package com.xuecheng.content.domain.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.domain.feignclient.MediaServiceClient;
import com.xuecheng.content.domain.mapper.CoursePublishMapper;
import com.xuecheng.content.domain.model.dto.CoursePreviewDto;
import com.xuecheng.content.domain.model.entity.CourseBase;
import com.xuecheng.content.domain.service.CourseBaseService;
import com.xuecheng.content.domain.service.CoursePublishService;
import com.xuecheng.content.domain.model.entity.CoursePublish;
import com.xuecheng.content.infrastructure.config.MultipartSupportConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private MediaServiceClient mediaServiceClient;

    @Override
    public File generateCourseHtml(Long courseId) {
        if (Objects.isNull(courseId)) {
            log.error("课程ID不存在");
            return null;
        }
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 最终的静态文件
        File htmlFile = null;
        try {
            // 获取resource路径
            String resourcesPath = URLDecoder.decode(this.getClass().getResource("/").getPath(), "utf-8");
            // 指定模板
            configuration.setDirectoryForTemplateLoading(new File(resourcesPath + "/templates/"));
            // 置顶编码格式
            configuration.setDefaultEncoding("utf-8");
            // 获取模板
            Template template = configuration.getTemplate("course_template.ftl");
            // 获取数据
            CoursePreviewDto coursePreviewDto = courseBaseService.queryCourseBasePreview(courseId);
            if (Objects.isNull(coursePreviewDto)){
                log.error("课程不存在");
                return null;
            }
            Map<String, CoursePreviewDto> data = new HashMap<>();
            data.put("model", coursePreviewDto);
            // 模板和数据整合
            String htmlStr = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
            // 输入流
            InputStream inputStream = IOUtils.toInputStream(htmlStr, "utf-8");
            htmlFile = File.createTempFile("course_publish", "html");
            // 输出流
            FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
            // 使用流将html写入文件
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (Exception e){
            log.error("生成课程静态页面出错，{}", e.getMessage());
        }

        return htmlFile;
    }

    @Override
    public void addHtmlToMinio(File file, Long courseId) {
        if (Objects.isNull(file) || file.length() == 0){
            return;
        }

        // 转为multipartFile
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        mediaServiceClient.upload(multipartFile, getObjectName(courseId));
    }

    private String getObjectName(Long courseId) {
        return "course/" + courseId + ".html";
    }
}
